﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Core
{
    public static partial class contest
    {
        public static dynamic getAutoContestPid(int cid)
        {
            var sql = new Sql.SqlDataContext();
            var result = from p in sql.ContestProblem
                      where p.cid == cid
                      orderby p.ps
                      select p.ps;
            var resultPid = from pro in sql.ContestProblem
                            orderby pro.pid
                            select pro.pid;

            var first = result.FirstOrDefault();
            var firstPid = resultPid.FirstOrDefault();

            if (!resultPid.Any())
            {
                return new
                {
                    pid = 1000,
                    ps = 'A',
                    success = true
                };
            }
            foreach(var pid in resultPid)
            {
                if (pid - firstPid > 1) break;
                firstPid = pid;
            }
            if (first != 'A')
            {
                return new
                {
                    ps = 'A',
                    pid = firstPid + 1,
                    success = true
                };
            }
            foreach(var p in result)
            {
                if (p - first > 1) break;
                first = p;
            }
            return new
            {
                pid = firstPid + 1,
                ps = Convert.ToChar(first + 1),
                success = true
            };
        }
    }
}
